package com.web;

import io.opentracing.mock.MockSpan;
import io.opentracing.mock.MockTracer;
import io.opentracing.tag.Tags;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Handler;

public class MyInterceptor implements HandlerInterceptor {

//    private static final MockSpan span = new MockTracer().buildSpan("foo").start();

    private static final ThreadLocal<Long> startTimeThreadLocal =
            new NamedThreadLocal<Long>("ThreadLocal StartTime");


    private static final ThreadLocal<MockSpan> spanThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //System.out.println("1----preHandle");
        MockSpan span = new MockTracer().buildSpan(httpServletRequest.getServletPath()).start();
        spanThreadLocal.set(span);
        span.setTag(Tags.COMPONENT, "my-own-application");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println(httpServletRequest.getServletPath());
        //System.out.println("2----postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        MockSpan span = spanThreadLocal.get();
        span.finish();
        System.out.println(String.format("Operation name = %s,Start = %s,Finish = %s,共执行：%s s",
                span.operationName(),span.startMicros(),span.finishMicros(),(span.finishMicros()-span.startMicros())/(1000*1000)));
        //System.out.println("3----afterCompletion");
    }
}
